package com.weiweiqin.service.impl;

import com.weiweiqin.model.*;
import com.weiweiqin.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

@Service
public class GameServiceImpl implements GameService {
	@Autowired
	private GamelogService gamelogService;

	@Autowired
	private PrizeService prizeService;

	@Autowired
	private CustomerService customerService;

	@Autowired
	private GoodsService goodsService;

	@Autowired
	private IntegrallogService integrallogService;

	@Override
	@Transactional
	public int gameStart(int goodsId, Customer customer){
		Goods goods = goodsService.get(goodsId);
		int gameNum = goods.getGameNum();
		BigDecimal amount = customer.getAmount();
		//后端再次验证是否余额不足
		if(amount.intValue() <gameNum) {
			return -1;
		}
		Gamelog gamelog = new Gamelog();
		gamelog.setAmount(gameNum);
		gamelog.setCreateTime(new Date());
		gamelog.setCustomerId(customer.getId());
		gamelog.setGoodsId(goodsId);
		gamelog.setLevel(1);
		gamelog.setResults(0);
		gamelogService.save(gamelog);
		//扣除金币
		int leafMoeny = customer.getAmount().intValue() - gamelog.getAmount();
		customer.setAmount(new BigDecimal(leafMoeny));
		customerService.update(customer);
		return gamelog.getId();
	}


	@Override
	@Transactional
	public void gameSuccess(int goodsId, int customerId, int level,int gameId) {
		Customer customer = customerService.get(customerId);
		Gamelog gamelog = gamelogService.get(gameId);
		gamelog.setEndTime(new Date());
		gamelog.setLevel(level);
		gamelog.setResults(2);
		gamelogService.update(gamelog);
		Prize prize = new Prize();
		prize.setCreateTime(new Date());
		prize.setCustomerId(customerId);
		prize.setGoodsId(goodsId);
		prize.setStatus(1);
		prizeService.save(prize);
		Integrallog integrallog = new Integrallog();
		integrallog.setCreateTime(new Date());
		integrallog.setCustomerId(customerId);
		integrallog.setGoodsId(gamelog.getGoodsId());
		integrallog.setIntegral(customer.getIntegral());
		integrallog.setType(2);
		//积分日志
		integrallogService.save(integrallog);
		//清空积分
		customer.setIntegral(0);
		customerService.update(customer);
	}

	@Override
	@Transactional
	public void gameFail(int customerId, int level,int gameId) {
		Customer customer = customerService.get(customerId);
		Gamelog gamelog = gamelogService.get(gameId);
		gamelog.setEndTime(new Date());
		gamelog.setLevel(level);
		gamelog.setResults(1);
		Integrallog integrallog = new Integrallog();
		integrallog.setCreateTime(new Date());
		integrallog.setCustomerId(customerId);
		integrallog.setGoodsId(gamelog.getGoodsId());
		integrallog.setIntegral(gamelog.getAmount());
		integrallog.setType(1);
		integrallogService.save(integrallog);
		gamelogService.update(gamelog);
		//奖励对应的积分
		customer.setIntegral(customer.getIntegral()+gamelog.getAmount());
		customerService.update(customer);
	}
}